package session2

import (
	"gitee.com/chejiangyi/bsfgo/core/base2"
	"github.com/gin-contrib/sessions"
	"github.com/gin-contrib/sessions/cookie"
	"github.com/gin-contrib/sessions/redis"
	"github.com/gin-gonic/gin"
)

var SessionUtil = &SessionUtilTool{}

type SessionUtilTool struct{}

func (*SessionUtilTool) InitSession(router *gin.Engine) {
	// 配置 Session 中间件
	var store sessions.Store
	if base2.BsfConfigInstance.GetSessionMode() == "cookie" {
		store = cookie.NewStore([]byte(base2.BsfConfigInstance.GetSessionSecretKey()))
	}
	if base2.BsfConfigInstance.GetSessionMode() == "redis2" {
		// 配置 Redis Session 存储
		store2, err := redis.NewStore(
			base2.BsfConfigInstance.GetSessionRedisMinPoolSize(), // 最大空闲连接数
			"tcp", // 网络类型
			base2.BsfConfigInstance.GetSessionRedisAddress(),  // Redis 地址
			base2.BsfConfigInstance.GetSessionRedisUsername(), // Redis 密码（没有密码留空）
			base2.BsfConfigInstance.GetSessionRedisPassword(),
			[]byte(base2.BsfConfigInstance.GetSessionSecretKey()), // Session 加密密钥
		)
		if err != nil {
			panic(base2.NewBsfBizError2("session2 redis2 模式初始化失败", err))
		}
		store = store2
	}
	store.Options(sessions.Options{
		Path:     base2.BsfConfigInstance.GetSessionPath(),     // 对所有路径有效
		Domain:   base2.BsfConfigInstance.GetSessionDomain(),   // 当前域名
		HttpOnly: base2.BsfConfigInstance.GetSessionHttpOnly(), // 防止 XSS
		Secure:   base2.BsfConfigInstance.GetSessionSecure(),   // 仅 HTTPS
		MaxAge:   base2.BsfConfigInstance.GetSessionMaxAge(),   // 过期时间(秒)
		SameSite: base2.BsfConfigInstance.GetSessionSameSite(),
	})
	router.Use(sessions.Sessions("bsfSession", store))
}

// New 创建SessionProxy实例
func (*SessionUtilTool) GetSessionDefault(c *gin.Context) *SessionProxy {
	return &SessionProxy{
		session: sessions.Default(c),
	}
}
